package com.piece.file.preview;

import com.piece.core.framework.util.file.FileCharsetDetector;
import com.piece.core.framework.util.file.FileUtil;
import com.piece.core.framework.util.net.HttpUtil;
import com.piece.file.support.FileAttribute;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * 处理文本文件
 */
@Slf4j
@Service
public class SimTextFilePreview implements FilePreviewHandle {

    @Override
    public String handle(FileAttribute fileAttribute, HttpServletRequest request, Model model, boolean edit) {
        String content = HttpUtil.get(fileAttribute.getUrl()).charset(FileUtil.getSystemCharset()).execute().text();
        model.addAttribute("content", content);
        model.addAttribute("key", fileAttribute.getKey());
        model.addAttribute("edit", edit);
        return "/file/txt";
    }

    /**
     * 转换文本文件编码为utf8
     */
    private void convertTextPlainFileCharsetToUtf8(String filePath) throws IOException {
        File sourceFile = new File(filePath);
        if (sourceFile.exists() && sourceFile.isFile() && sourceFile.canRead()) {
            String encoding = null;
            try {
                FileCharsetDetector.Observer observer = FileCharsetDetector.guessFileEncoding(sourceFile);
                // 大部分文件都是windows系统产生的可以考虑使用GBK
                encoding = observer.isFound() ? observer.getEncoding() : "GBK";
            } catch (IOException e) {
                log.error("编码探测异常：{}", e.getMessage());
            }
            if (null != encoding && !"UTF-8".equalsIgnoreCase(encoding)) {
                // 不为utf8,进行转码
                File tmpUtf8File = new File(filePath + ".utf8");
                Writer writer = new OutputStreamWriter(new FileOutputStream(tmpUtf8File), "UTF-8");
                Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile), encoding));
                char[] buf = new char[1024];
                int read;
                while ((read = reader.read(buf)) > 0) {
                    writer.write(buf, 0, read);
                }
                reader.close();
                writer.close();
                // 删除源文件
                sourceFile.delete();
                // 重命名
                tmpUtf8File.renameTo(sourceFile);
            }
        }
    }
}
